import router from "@/router"
import { myMenu } from "@/api/login"
import { menu2Router } from "@/utils/formatMenu"

import redirectRouter from "@/router/redirectRouter"

export default {
  namespaced: true,
  state: {
    routes: [],
    sidebarMenu: redirectRouter,
    outUrl: ""
  },
  mutations: {
    SET_ROUTES(state, payload) {
      state.routes = payload
    },
    CHANGE_ROUTES(state, payload) {
      if (payload < 0) {
        state.sidebarMenu = redirectRouter
        return
      }
      state.sidebarMenu = state.routes[payload].children
    },
    CHANGE_OUTURL(state, plyload) {
      state.outUrl = plyload
    }
  },
  actions: {
    getRouteAction({ commit }) {
      myMenu().then((res) => {
        const routes = menu2Router(res.data, true)
        commit("SET_ROUTES", routes)
        commit("CHANGE_ROUTES", 0)
        router.addRoutes(routes)
      })
    }
  }
}
